#!/usr/bin/env python
# coding=utf-8
import akshare as ak
import pandas as pd
import numpy as np
import time
from include import dataBase
from include import dealCode

class dealHistory:
    def __init__(self,connect):
        self.connect = connect
        self.dealCode = dealCode.dealCode(connect)
        self.baseName = ""

    def saveOne(self,code):
        sql = '''  CREATE TABLE IF NOT EXISTS `{}` (
            date DATE NOT NULL,
            openPrice DECIMAL(10, 2) NOT NULL,
            closePrice DECIMAL(10, 2) NOT NULL,
            highPrice DECIMAL(10, 2) NOT NULL,
            lowPrice DECIMAL(10, 2) NOT NULL,
            volume INT NOT NULL,
            turnover DECIMAL(20, 2) NOT NULL,
            amplitude DECIMAL(7, 2) NOT NULL,
            changePercent DECIMAL(7, 2) NOT NULL,
            changeAmount DECIMAL(10, 2) NOT NULL,
            turnoverRate DECIMAL(7, 2) NOT NULL,
            isTop INT NOT NULL,
            topAllDayNum INT NOT NULL,
            topDayNum INT NOT NULL,
            PRIMARY KEY (date)
            );  '''.format(code + "X")
        self.connect.create(code + "X",sql)
        ''' 短时间请求过多会封ip  '''
        #try:
        if 1 == 1:
            print("code = " + code)
            print(type(code))
            data = ak.stock_zh_a_hist(symbol=code)
            # 查询表中日期，进行更新数据
            maxDate = self.connect.selectMax(code + 'X',"code")
            if maxDate != -1:
                newData = data[data["日期"] > maxDate]
            else:
                newData = data
            
            print("更新:{},更新行数:{}".format(code,len(newData)))
            
            for date in newData.itertuples():
                isTop = self.isTop(code,date[4],date[11])
                sql = ''' insert into `{}` values('{}',{},{},{},{},{},{},{},{},{},{},{},{},{})
                on duplicate key update `date` = `date`;
                '''.format(codei + "X",date[1],date[3],date[4],date[5],date[6],date[7],round(date[8]/10**8,2),
                           date[9],date[10],date[11],date[12],isTop,0,0)
                result = self.connect.insert(code,sql)
                self.connect.commit()
                return result
        #except:
            #print("请等待60S")
            #time.sleep(60)
            #return -1

    def saveAll(self):
        allCode = self.dealCode.getAllCode()
        for (code,) in allCode:
            self.saveOne(code)


    def isTop(self,code,closePrice,changeAmount):
        if(code[0] != '3' or code[0:2] in ['68','69']):
            if(round((closePrice - changeAmount)*1.1,2) == closePrice):
                isTop = 1
            else:
                isTop = 0
        else:
            if(round((closePrice - changeAmount)*1.1,2) <= closePrice):
                isTop = 1
            elif(round((closePrice - changeAmount)*1.2,2) == closePrice):
                isTop = 2
            else:
                isTop = 0
        return isTop

    def isDown(self):
        if(code[0] != '3' or code[0:2] in ['68','69']):
            if(round((closePrice - changeAmount)*0.9,2) == closePrice):
                isDown = 1
            else:
                isDown = 0
        else:
            if(round((closePrice - changeAmount)*0.9,2) <= closePrice):
                isDown = 1
            elif(round((closePrice - changeAmount)*0.8,2) == closePrice):
                isDown = 2
            else:
                isDown = 0
        return isDown

    def getTopDay(self):
        allCode = self.dealCode.getAllCode()
        # 断板天数
        breakNum = 4
        for (code,) in allCode:
            print("getTopDasy : " + code)
            
            if self.connect.show(code) == 0:
                print("没有这个表" + code)
                return -1

            sql = ''' select date,isTop,topAllDayNum,topDayNum from `{}`;  '''.format(code)
            data = list(zip(*self.connect.select(code,sql)))

            if len(data) == 0:
                continue

            date = list(data[0])
            isTop = list(data[1])
            topAllDayNum = list(data[2])
            topDayNum = list(data[3])
            lastIndex = -1
            lastDateIndex = -9

            # 尝试找到最后一次处理的结果
            indices = [i for i,value in enumerate(topAllDayNum) if value != 0]
            lastIndex = indices[-1] if indices else -1
            # 若没有，则通过查找最后一次涨停判断是未处理的数据还是涨停数为0的数据
            if(lastIndex == -1):
                indices = [i for i, value in enumerate(isTop) if value != 0]
                lastIndex = indices[-1] if indices else -1
            # 这个也没有，说明不需要处理,不计算第一天数据
            if(lastIndex == -1):
                continue
            else:
                lastIndex = 1
            # 从之前处理的最后一次开始处理
            for i in range(lastIndex,len(date)):
                tempTop = isTop[i]
                if(tempTop == 0):
                    continue

                if(lastDateIndex + breakNum >= i):
                    topAllDayNum[i] = topAllDayNum[lastDateIndex] + tempTop + i - lastDateIndex -1
                    topDayNum[i] = topDayNum[lastDateIndex] + tempTop
                else:
                    topAllDayNum[i] = topAllDayNum[i - 1] + tempTop
                    topDayNum[i] = topDayNum[i - 1] + tempTop

                sql = "update `{}` set topAllDayNum={},topDayNum={} where date='{}';".format(
                    code,topAllDayNum[i],topDayNum[i],date[i])
                self.connect.update(code,sql)
                lastDateIndex = i

            self.connect.commit()

        return 0

    def getTopTrend(self,code):
        pass

    def getDownTrend(self,code):
        pass

    def getRangeIncrease(self,code,beginDate,endDate):
        pass

    def getDateHistory(self,date,code):
        sql = ''' select * from `{}` where date='{}' '''.format(code,date)
        #print(sql)
        return self.connect.select(code,sql)
